package com.ysd.upload.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import com.ysd.upload.common.AliyunConfig;
import com.ysd.upload.service.AliyunUpload;

public class AliyunUploadImpl implements AliyunUpload{
	/**
	 * 断点续传
	 * @throws Exception 
	 */
	@Override
	public String uploadFile(String uploadFile, String savePathName) throws Exception {
		OSSClient ossClient = new OSSClient(AliyunConfig.endpoint, AliyunConfig.accessKeyId,
				AliyunConfig.accessKeySecret);
		try {
			UploadFileRequest uploadFileRequest = new UploadFileRequest(AliyunConfig.bucketName, savePathName);
			// 待上传的本地文件
			uploadFileRequest.setUploadFile(uploadFile);
			// 设置并发下载数，默认1
			uploadFileRequest.setTaskNum(5);
			// 设置分片大小，默认100KB
			uploadFileRequest.setPartSize(1024 * 1024 * 1);
			// 开启断点续传，默认关闭
			uploadFileRequest.setEnableCheckpoint(true);
			
			UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
			
			CompleteMultipartUploadResult multipartUploadResult = uploadResult.getMultipartUploadResult();
			return multipartUploadResult.getLocation();
		} catch (OSSException oe) {
			throw oe;
		} catch (ClientException ce) {
			throw ce;
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			ossClient.shutdown();
		}
		return null;
	}
}
